// ProfileDataScreen.kt
package com.example.nutritionmanager.profile

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.example.nutritionmanager.UserProfile
import com.example.nutritionmanager.viewModels.UserProfileState
import com.example.nutritionmanager.viewModels.UserProfileViewModel
import com.example.nutritionmanager.buttons.PrimaryButton
import kotlinx.coroutines.launch

@Composable
fun ProfileDataScreen(
    navController: NavController,
    userProfileViewModel: UserProfileViewModel = hiltViewModel()
) {
    val userProfileState by userProfileViewModel.userProfileState.collectAsState()
    val snackbarHostState = remember { SnackbarHostState() }
    val coroutineScope = rememberCoroutineScope()

    // 定义可变状态变量
    var username by remember { mutableStateOf("") }
    var gender by remember { mutableStateOf("") }
    var height by remember { mutableStateOf("") }
    var weight by remember { mutableStateOf("") }

    // 在Composable首次启动时获取用户资料
    LaunchedEffect(Unit) {
        userProfileViewModel.fetchUserProfile()
    }

    // 监听错误信息并通过Snackbar展示
    LaunchedEffect(userProfileState) {
        if (userProfileState is UserProfileState.Error) {
            val errorMessage = (userProfileState as UserProfileState.Error).error
            coroutineScope.launch {
                snackbarHostState.showSnackbar(errorMessage)
            }
        }
        // 监听保存成功逻辑 (假设有 SaveSuccess 状态)
        // 如果需要，可以在 ViewModel 中添加 SaveSuccess 状态
    }

    // 当用户资料成功获取后，初始化输入字段的值
    LaunchedEffect(userProfileState) {
        if (userProfileState is UserProfileState.Success) {
            val userProfile = (userProfileState as UserProfileState.Success).userProfile
            username = userProfile.username
            gender = userProfile.gender
            height = userProfile.height
            weight = userProfile.weight
            // 您可以添加更多初始化逻辑，例如目标期
        }
    }

    Scaffold(
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0xFFf1f1f1))  // 设置背景为灰色
                .padding(16.dp)
                .verticalScroll(rememberScrollState()) // 使页面可滑动
                .padding(paddingValues) // 处理 Scaffold 的内边距
        ) {
            Text(
                text = "编辑个人资料",
                fontSize = 20.sp,
                color = Color.Black,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 16.dp)
            )
            when (userProfileState) {
                is UserProfileState.Loading -> {
                    // 显示加载中的进度条
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(100.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator()
                    }
                }
                is UserProfileState.Idle -> {
                    // 初始状态，可以显示一个空界面或提示
                    Text(text = "正在加载...", color = Color.Gray)
                }
                is UserProfileState.Error -> {
                    // 错误状态，错误信息已通过Snackbar展示
                    // 可以在此处添加额外的错误处理 UI
                    Text(
                        text = "加载失败，请重试。",
                        color = Color.Red,
                        modifier = Modifier.padding(top = 16.dp)
                    )
                }
                is UserProfileState.Success -> {
                    val userProfile = (userProfileState as UserProfileState.Success).userProfile
                    ProfileInputField(label = "用户名", value = username) { username = it }
                    ProfileInputField(label = "性别", value = gender) { gender = it }
                    ProfileInputField(label = "身高 (cm)", value = height) { height = it }
                    ProfileInputField(label = "体重 (kg)", value = weight) { weight = it }
                }
            }

            Spacer(modifier = Modifier.height(24.dp))

            PrimaryButton(
                onClick = {
                    // 创建更新后的用户资料对象
                    val updatedProfile = UserProfile(
                        username = username,
                        age = "20",
                        gender = gender,
                        height = height,
                        weight = weight,
                        period = "1",
                        registerDate = "", // 根据需要填充
                        targetCalories = "2000"
                    )
                    userProfileViewModel.updateUserProfile(updatedProfile)

                    // 返回上一个页面
                    navController.popBackStack()
                },
                modifier = Modifier.fillMaxWidth(),
                text = "保存"
            )
        }
    }
}